package com.alinesno.cloud.operation.cmdb.third.email;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alinesno.cloud.operation.cmdb.common.constants.EmailSendStatus;
import com.alinesno.cloud.operation.cmdb.entity.EmailEntity;

/**
 * 发送服务
 * @author WeiXiaoJin
 * @since 2018年8月29日 下午8:48:03
 */
@Service
public class RunEmailService {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@SuppressWarnings("unused")
	private static String inviteRunManStr = null ;  //发送用户邀请
	@SuppressWarnings("unused")
	private static String inviteMemberStr = null ;  //发送会员邀请
	private static String inviteZhoneqiuStr = null ;  //发送会员邀请
	
	public static int MAX_SEND_SIZE = 200 ; //每次发送条数
	public static int DAY_MAX_SEND = 100000 ; //每天最大发送条数

	@Autowired
	private EmailService emailService ; 
	
//	//初始化邮件信息
//	static {
//		try {
//			File file = ResourceUtils.getFile("classpath:email/invite_runman_email.html");
//			inviteRunManStr = RunStringUtils.readToString(file) ;  
//			
//			File file2 = ResourceUtils.getFile("classpath:email/invite_email.html");
//			inviteMemberStr = RunStringUtils.readToString(file2) ;  
//			
//			File file3 = ResourceUtils.getFile("classpath:email/invite_zhongqiu.html");
//			inviteZhoneqiuStr = RunStringUtils.readToString(file3) ;  
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		}
//	}


	/**
	 * 发送信息招募人员信息<br/>
	 */
	public void sendRunmanEmail() {
	
		int count = emailService.findDaySend(EmailSendStatus.SEND) ; //查询当天已发送数量
		if(count >= DAY_MAX_SEND) {
			return ; 
		}
		
		String title = "民大云主机管理系统中秋免费送月饼上门" ; 
		List<EmailEntity> emails = emailService.findLimit(MAX_SEND_SIZE) ; 
		logger.debug("inviteZhoneqiuStr = {}" , inviteZhoneqiuStr);
		if(emails != null) {
			for(EmailEntity e: emails) {
				try {
					emailService.sendSingleEmail(e.getEmail(), e.getEmailOwner()+","+title, inviteZhoneqiuStr) ; 
					e.setSendTime(e.getSendTime()+1);
					e.setUpdateTime(new Date());
					
					logger.debug("发送邮件{}成功." , e.getEmail());
				}catch(Exception e1) {
					logger.error("发送邮件{}失败" , e.getEmail());
					e.setLastSendFilaTime(new Date());
					e.setFailTime(e.getFailTime()+1);
					e.setFailDesc(e1.getMessage());
				}
				e.setRendStatus(EmailSendStatus.NO_SEND.getValue()); 
				emailService.update(e) ; 
			}
		}
	}
	
}
